package com.idconfirmsystem.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.kymjs.kjframe.http.HttpCallBack;

import u.aly.br;
import u.aly.q;

import com.idconfirmsystem.Conf;
import com.idconfirmsystem.Constants;
import com.idconfirmsystem.R;
import com.idconfirmsystem.handler.TaskDetailHandler;
import com.idconfirmsystem.model.BranchTask;
import com.idconfirmsystem.model.BranchTaskList;
import com.idconfirmsystem.model.BranchTaskQuery;
import com.idconfirmsystem.model.QueryRet;
import com.idconfirmsystem.model.Task;
import com.idconfirmsystem.model.UserBean;
import com.idconfirmsystem.parse.BranchParse;
import com.idconfirmsystem.remote.ConfirmApi;
import com.idconfirmsystem.remote.TaskApi;
import com.idconfirmsystem.util.DateUtil;
import com.idconfirmsystem.util.FileUtils;
import com.idconfirmsystem.util.XmlUtils;

import android.os.Bundle;
import android.os.Handler;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class TaskDetailActivity extends Activity {

	// handler
	private Handler handler = new TaskDetailHandler(this);

	// 布局元素
	private Element el = new Element();

	private class Element {
		private TextView taskNum;
		private TextView startTime;
		private TextView pilotman;
		private TextView driver;
		private TextView carNum;
		private TextView protectOne;
		private TextView protectTwo;
		private Button addButton;
		TextView[] detaiTextViews = { taskNum, startTime, pilotman, driver, carNum, protectOne, protectTwo };

		private TableLayout taskTableLayout;
	};

	private Context context = TaskDetailActivity.this;
	// 运行时临时变量
	private RuntimeObject ru = new RuntimeObject();

	private class RuntimeObject {
		String[] detailString = { "任务编号：", "出发日期：" + DateUtil.getCurrentDateByFormat("yyyyMMdd"), "业务员：", "驾驶员：",
				"车辆牌号：\n\t\t\t\t", "护卫1\t：", "护卫2\t：" };

		private BranchParse branchParse;
		private Boolean isZHUser;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ru.isZHUser = UserBean.getInstance().getType().equals("KH")
				&& Conf.TaskConf.KHUserType.equals("ZH");
		if (ru.isZHUser) {
			setContentView(R.layout.activity_cur_task);
		} else {
			setContentView(R.layout.activity_task);
		}

		ActionBar ab = getActionBar();
		ab.setDisplayHomeAsUpEnabled(true);
		ab.setHomeButtonEnabled(true);
		setTitle("任务详情");

		Bundle bundle = getIntent().getExtras();
		initView();
		querySubTaskList(bundle.getString("taskid"));

	}

	private void initView() {
		el.taskNum = (TextView) findViewById(R.id.task_num);
		el.startTime = (TextView) findViewById(R.id.task_start_time);
		el.pilotman = (TextView) findViewById(R.id.task_salesman);
		el.driver = (TextView) findViewById(R.id.task_driver);
		el.carNum = (TextView) findViewById(R.id.task_car_num);
		el.protectOne = (TextView) findViewById(R.id.task_protect1);
		el.protectTwo = (TextView) findViewById(R.id.task_protect2);
		// for (int i = 0; i < el.detaiTextViews.length; i++) {
		// el.detaiTextViews[i].setText(ru.detailString[i]);
		// }
		el.addButton = (Button) findViewById(R.id.add_btn);
		if (UserBean.getInstance().getType().equals("KH")) {
			el.addButton.setVisibility(View.VISIBLE);
		} else {
			el.addButton.setVisibility(View.INVISIBLE);
		}
		el.addButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				if (Conf.TaskConf.TaskType.equals("A")) {
					intent.setClass(TaskDetailActivity.this, CreatMoneyTaskActivity.class);
				} else {
					intent.setClass(TaskDetailActivity.this, AddTaskActivity.class);
				} 
				startActivity(intent);
			}
		});
		el.taskTableLayout = (TableLayout) findViewById(R.id.task_tablelayout);
		initViewData();
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.task, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}


	public void querySubTaskList(final String taskid) {
		BranchTaskQuery query = new BranchTaskQuery();
		query.setTaskId(taskid);
		query.setBranchNumber(UserBean.getInstance().getBranchNumber());

		String serviceMethod = "TaskService/getTaskBranchList";

		ConfirmApi.queryData(query, serviceMethod, callBack);
	}

	public void updateData() {
		List<BranchTask> branchTasks = null;
		if (ret == null) {
			return;
		}
		if (ret.getTotalnum() <= 0) {

		}
		BranchTaskList blist = ret.getResult();

		if (blist == null || blist.getBranchTasks() == null
				|| blist.getBranchTasks().size() <= 0) {
			branchTasks = new ArrayList<BranchTask>();
		} else {
			branchTasks = blist.getBranchTasks();
		}
		if (!ru.isZHUser) {
			for (int i = 0; i < branchTasks.size(); i++) {
				addTable(branchTasks.get(i));
			}
		}

	}

	private void initViewData(){
		el.taskNum.setText(ru.detailString[0] + Conf.TaskProcess.curTask.getId());
		el.startTime.setText(ru.detailString[1]);
		el.pilotman.setText(ru.detailString[2] + Conf.TaskProcess.curTask.getPilot_name());
		el.driver.setText(ru.detailString[3] + Conf.TaskProcess.curTask.getClerk_name());
		el.carNum.setText(ru.detailString[4] + Conf.TaskProcess.curTask.getCar_name());
		el.protectOne.setText(ru.detailString[5] + Conf.TaskProcess.curTask.getEscort_name1());
		el.protectTwo.setText(ru.detailString[6] + Conf.TaskProcess.curTask.getEscort_name2());

	}


	QueryRet<BranchTaskList> ret;
	HttpCallBack callBack = new HttpCallBack() {

		@Override
		public void onFailure(int errorNo, String strMsg) {
			// TODO Auto-generated method stub
			super.onFailure(errorNo, strMsg);
			Toast.makeText(getApplicationContext(), errorNo+":"+strMsg, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onSuccess(String t) {
			// TODO Auto-generated method stub
			super.onSuccess(t);
			try {
				ret = XmlUtils.toBean(BranchTaskList.class, t);
				Log.d("aa",t);
				updateData();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

	};


	public void addTable(BranchTask item){
		TableRow tr = new TableRow(context);
		TextView tv1 = new TextView(context);
		TextView tv2 = new TextView(context);
		TextView tv3 = new TextView(context);
		TextView tv4 = new TextView(context);
		TextView tv5 = new TextView(context);
		TextView tv6 = new TextView(context);
		String branchInfo = item.getCoordinateTitle();
		// String branchInfo = "" + data.get("branch_number")
		// + data.get("coordinate_title");
		tv1.setText(branchInfo);
		tv1.setGravity(Gravity.CENTER_HORIZONTAL);
		tv2.setText("08:30");
		tv2.setGravity(Gravity.CENTER_HORIZONTAL);
		tv3.setText("10:30");
		tv3.setGravity(Gravity.CENTER_HORIZONTAL);
		int verifyFlag =0;
		try {
			verifyFlag = Integer.parseInt( item.getVerifyFlag());
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (verifyFlag == 0) {
			tv5.setText("待交接");
			tv5.setTextColor(getResources().getColor(R.color.red));
			tv5.setGravity(Gravity.CENTER_HORIZONTAL);
			tv6.setText("身份确认");
			tv6.setGravity(Gravity.CENTER_HORIZONTAL);
			tv6.setTextColor(getResources().getColor(R.color.darkblue));
		} else {
			tv5.setText("已交接");
			tv5.setTextColor(getResources().getColor(R.color.blue));
			tv5.setGravity(Gravity.CENTER_HORIZONTAL);
			String verifyTime = item.getVerifyTime();
			tv4.setText(verifyTime);// 交接时间
			tv4.setGravity(Gravity.CENTER_HORIZONTAL);
		}
		tv6.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(context, IdConfirmActivity.class);
				startActivity(intent);
			}
		});
		tr.addView(tv1);
		// tr.addView(tv2);
		// tr.addView(tv3);
		tr.addView(tv5);
		tr.addView(tv4);
		tr.addView(tv6);
		tr.setPadding(0, 12, 0, 12);
		tr.setBackground(getApplication().getResources().getDrawable(
				R.drawable.table_row));
		// 实现单击查看支行案件详情
		tr.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startActivity(new Intent(TaskDetailActivity.this,
						TaskDetailDialog.class));
			}
		});
		View line = new View(context);
		line.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
		line.setBackgroundColor(getResources().getColor(R.color.black));
		el.taskTableLayout.addView(line);
		el.taskTableLayout.addView(tr);
	}
}
